;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var quCode = null;
    var pageSize = 10;
    var category_id_p = param_map.category_id;
    var _category_id;
    var global_param_map;
    
	 $( function () {
		App.init();
		$("#head_login_status").empty();
		//$("#head_login_status").append($("#dowanload"));
		if(!App.checkLogin()){
			global_param_map = {};
			$("#head_login_status").append($("#un_login_template"));
		} else {
			global_param_map = App.getCookeData();
			$("#_user_name").html(global_param_map["nickname"]);
			if(global_param_map["user_icon"] !== undefined && global_param_map["user_icon"] != null 
				&& global_param_map["user_icon"] != ""){
				$("#_head_pic").attr("src", Interface.image.pre + global_param_map["user_icon"]);
			}
			$("#head_login_status").append($("#already_login_template"));
			refushToken(global_param_map['token']);
		}

		 
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }

		 loadLeftCategory();
		 loadBranner();
		 $("#search").click(function(){
			 $("#left_category_list li.second").removeClass("active");
			 _category_id = "";
			 loadCategoryList();
		 });
		 loadRaceJingcai();
		 loadRaceGonggao();
		 
	 });
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
  			  	loadLeftCategory();
				loadBranner();
				loadRaceJingcai();
				loadRaceGonggao();
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
  			  	loadLeftCategory();
				loadBranner();
				loadRaceJingcai();
				loadRaceGonggao();
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 
	 function loadBranner(){
		 Result.doResult( {
			 url:  Interface.zs.adQrAdvInfos,
			 data: {"type" : 1, "orgCode" : quCode},
			 type: "POST",
		 }, function ( data ) {
			 //banner
			 var $bannerTemplate = $( "#banner_template" ),
    			 $bannerList = $("#banner_list");
			 $bannerList.empty();
			 if( $.isArray( data ) ) {
				 for( var i = 0, l = data.length; i < l; i++ ) {
					 $bannerList.append( Result.fillData( $bannerTemplate.clone().removeAttr( "id" ), data[i], "field" ) );
	             }
				 $("#slider").flexslider();
			 }
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 function loadLeftCategory(){
		var params = {"orgCode" : quCode};
		var $template = $("#left_category_template"),
	 	 	$list = $("#left_category_list");
		$list.empty();
		Result.doResult( {
        	url: Interface.zs.articleQryTypes,
           	type: "POST",
           	async: false,
           	data : params
       	}, function ( data) {
			 $list.append($("#first"));
			 if(data.length > 0){
				 if( $.isArray( data ) ) {
		    		for( var i = 0, l = data.length; i < l; i++ ) {
		    			var obj = $template.clone().removeAttr( "id" );
		               	$list.append( Result.fillData( obj, data[i], "field" ));
		           }
		        }
				if(category_id_p == null || category_id_p == "" || category_id_p == 0){
					$("#left_category_list li.second").eq(0).removeClass("active").addClass("active");
					var fir = $("#left_category_list li.second").eq(0).find('a').attr('category_id');
					_category_id = fir;
				} else {
					_category_id = category_id_p;
					$("#left_category_list li.second").removeClass("active");
					$("#left_category_list li.second").find("a[category_id='"+category_id_p+"']").parent().addClass("active");
				}
					 
				 loadCategoryList();
				 $("#left_category_list li.second").click(function(){
					 $("#left_category_list li.second").removeClass("active");
					 $(this).addClass("active");
					 _category_id = $(this).find('a').attr("category_id");
					 loadCategoryList();
				 });
			 }
       	}, function ( desc ) {
            Result.alert( "暂无数据");
            $list.empty();
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
		 
	 }
	 
	 
	 
	 function loadCategoryList(){
		 var $template1 = $("#small_template"),
		 	 $template2 = $("#big_template"),
		 	 $template3 = $("#santu"),
		 	 $list = $("#news_list");
		 $list.empty();
		 
		 $('#news_list').scrollPagination({
            url: Interface.zs.articleQryArticleByType,
            beforeLoad: function(){
            },
            afterLoad:function(data){
           		var dataList = data.list;
           		if( $.isArray( dataList ) ) {
             		for( var i = 0, l = dataList.length; i < l; i++ ) {
             			var pl = dataList[i].cover_mode;
             			var obj;
             			if(pl == 1){
             				obj = $template1.clone().removeAttr( "id" );
             			} else if (pl == 2){
             				obj = $template2.clone().removeAttr( "id" );
             			} else {
             				obj = $template3.clone().removeAttr( "id" );
             			}
             			$list.append( Result.fillData( obj, dataList[i], "field" ));
                    }
                 }
           		init();
            },
            finished:function(page){
            },
            pageIndex:1,
            //pageSize:3,
            //totalItems:100000,
            offset:10,
            postData : {
                'orgCode' : quCode,
                'articleTypeId' : _category_id,
                'pSize' : pageSize,
                'articleTitle' : $("#search_title").val(),
                'userId' : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
                			&& global_param_map['id'] != '') ? global_param_map['id'] : 0,
            },
            vertical:false
        });
	 }
	 
	 
	 function init(){
		 $("#news_list").find(".to_detail").off().click(function(){
			 var newid = $(this).attr('new_id'),
			 	is_ad = $(this).attr('is_ad'),
			 	link = $(this).attr('link');
			 App.setReadNews(newid);
			 if(is_ad == 1){
				 window.open(link);
			 } else {
				 Result.forward("newsDetail.html", {"new_id" : newid});
			 }
		 });
		 
		 $("#news_list").find(".zanAction").off().click(function(){
			 var zu_id = $(this).attr("zu_id");
			 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
		     			|| global_param_map['id'] == ''){
				 alert("您还未登录");
				 return;
			 }
			 if($(this).hasClass("cur")){
				 alert("您已经点赞过了");
				 return;
			 }
			 dianzan(zu_id, $(this));
			 
		 });
		 
	 }
	 
	 //点赞
	 function dianzan(new_id, obj){
		 var params= {
		     "userId" : global_param_map['id'],
		     "articleId" : new_id,
		 };
		 Result.doResult( {
			 url: Interface.zs.articleUpVote,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			alert("点赞成功");
			obj.addClass("cur");
			var upvotes = obj.parent().find("div[field=upvotes_num]");
			var upvotes_num = upvotes.html();
			upvotes.html((parseInt(upvotes_num) + 1));
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 }
	 
	 function refushToken(token){
		 var params= {
		     "token" : token,
		 };
		 Result.doResult( {
			 url: Interface.zs.userRefreshToken,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			console.log(data);
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 }
	 
	 //赛事竞猜
	 function loadRaceJingcai(){
		 var race_jingcai_list = $("#race_jingcai_list"),
		 	saishi_jingcai_template = $("#saishi_jingcai_template");
		 race_jingcai_list.empty();
		 
		 Result.doResult( {
			 url:  Interface.zs.articleQryArticleByType,
			 data: {'orgCode' : quCode,
	                'pSize' : 6,
	                'cPage' : 1,
	                'userId' : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
	                			&& global_param_map['id'] != '') ? global_param_map['id'] : 0,
	                'objType' : 2},
			 type: "POST",
			 asyc : true,
		 }, function ( data ) {
			var dataList = data.list;
			if(dataList.length == 0){
				var str = '<div class="itemone" ><div class="font-color-1" >暂无数据</div></div>'
				race_jingcai_list.append(str);
			} else {
				if( $.isArray( dataList ) ) {
	         		for( var i = 0, l = dataList.length; i < l; i++ ) {
	         			var obj = saishi_jingcai_template.clone().removeAttr( "id" );
	         			obj.attr("sai_id", dataList[i].id);
	         			race_jingcai_list.append( Result.fillData( obj, dataList[i], "field" ));
	                }
	             }
				
				race_jingcai_list.find(".to_detail").off().click(function(){
					var id = $(this).attr("sai_id");
					Result.forward("raceNewsDetail.html", {"new_id" : id, "type" : 1});
					return;
				});
			}
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	//赛事公告
	 function loadRaceGonggao(){
		 var race_gonggao_list = $("#saishi_gonggao_list"),
		 	saishi_gonggao_template = $("#saishi_gonggao_template");
		 race_gonggao_list.empty();
		 
		 Result.doResult( {
			 url:  Interface.zs.articleQryArticleByType,
			 data: {'orgCode' : quCode,
	                'pSize' : 6,
	                'cPage' : 1,
	                'userId' : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
	                			&& global_param_map['id'] != '') ? global_param_map['id'] : 0,
	                'objType' : 3},
			 type: "POST",
			 asyc : true,
		 }, function ( data ) {
			console.log(data);
			var dataList = data.list;
			if(dataList.length == 0){
				var str = '<div class="itemone" ><div class="font-color-1" >暂无数据</div></div>'
				race_gonggao_list.append(str);
			} else {
				if( $.isArray( dataList ) ) {
	         		for( var i = 0, l = dataList.length; i < l; i++ ) {
	         			var obj = saishi_gonggao_template.clone().removeAttr( "id" );
	         			obj.attr("sai_id", dataList[i].id);
	         			if(dataList[i].cover_icon1 == null || dataList[i].cover_icon1 == ""){
	         				obj.find(".img_co").parent().hide();
	         			} else {
	         				obj.find(".img_co").parent().show();
	         				obj.find(".img_co").attr("src", Interface.image.pre + dataList[i]['cover_icon1']);
	         			}
	         			race_gonggao_list.append( Result.fillData( obj, dataList[i], "field" ));
	                }
	             }
					race_gonggao_list.find(".to_detail").off().click(function(){
					var id = $(this).attr("sai_id");
					Result.forward("raceNewsDetail.html", {"new_id" : id, "type" : 2});
					return;
				});
			}
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 window.replace_left_category_name = function ( $field, name, rowVal ) {
		$field.html(name);
		$field.attr("category_id", rowVal['id']);
		$field.attr("category_name", rowVal['name']);
	 };
	 
	 
	 window.replace_new_title = function ( $field, title, rowVal ) {
		$field.html(title);
		$field.attr("link", rowVal['ad_url']);
		$field.attr("new_id", rowVal['id']);
		$field.attr("is_ad", rowVal['is_ad']);
		if(App.getReadNews(rowVal['id'])){
			$field.removeClass("visited").addClass("visited");
		}
	 };
	 
	 window.replaceForward = function ( $field, title, rowVal ) {
		$field.attr("link", rowVal['ad_url']);
		$field.attr("new_id", rowVal['id']);
		$field.attr("is_ad", rowVal['is_ad']);
	 };
	 
	 
	 
	 window.replace_ad_is = function ( $field, ad, rowVal ) {
		 if(rowVal['is_ad'] == 1){
			 $field.empty();
			 $field.html('<span style="border:1px solid;border-radius:5px;padding:2px;">广告</span>');
		 }
	 };
	 
	 window.replace_date_time = function ( $field, datetime, rowVal ) {
		 if(datetime != null && datetime != ""){
			 $field.html(App.formateNewDateTime(datetime));
		 } else {
			 $field.html("");
		 }
		 
	 };
	 
	 
	 window.replaceIsZan = function ( $field, is_zan, rowVal ) {
		 if (global_param_map['id'] !== undefined && global_param_map['id'] != null 
     			&& global_param_map['id'] != '') {
			 if(is_zan == 1){
				 $field.addClass("cur");
			 } else {
				 $field.removeClass("cur");
			 }
		 }
		 $field.attr("zu_id", rowVal['id']);
	  };
	  
	  window.replace_article_source1 = function ( $field, article_source, rowVal ) {
		  if(rowVal['article_source'] == null || rowVal['article_source'] == ""){
			  $field.html("");
			  $field.css({"margin-right" : "0px", "margin-left" : "0px"});
		  } else{
			  $field.html("|");
			  $field.css({"margin-right" : "5px", "margin-left" : "5px"});
		  }
	  };
	  
	  window.replace_article_source2 = function ( $field, article_source, rowVal ) {
		  $field.html(rowVal['article_source']);
		  if(rowVal['article_source'] == null || rowVal['article_source'] == ""){
			  $field.css({"width" : "0px"});
		  } else{
			  $field.css({"width" : "100px"});
		  }
	  };
	  
	 
	 window.replace_images = function ( $field, id, rowVal ) {
		 var model = rowVal['cover_mode'];
		 if(model == 1){
			 $field.attr("src", Interface.image.pre + rowVal['cover_icon1']);
		 } else if (model == 2){
			 $field.attr("src", Interface.image.pre + rowVal['cover_icon1']);
		 } else if (model == 3){
			 $field.empty();
			 var $h = '<div class=" am-padding-right-sm am-fl"><a class="font-color-1"  href="javascript:void(0)">'+
				 '<img class="am-img-responsive" src="'+ Interface.image.pre + rowVal['cover_icon1']+'"></a></div>';
			 $field.append($h);
			 $h = '<div class=" am-padding-right-sm am-fl"><a class="font-color-1"  href="javascript:void(0)">'+
			 '<img class="am-img-responsive" src="'+Interface.image.pre + rowVal['cover_icon2']+'"></a></div>';
			 $field.append($h);
			 $h = '<div class=" am-padding-right-sm am-fl"><a class="font-color-1"  href="javascript:void(0)">'+
			 '<img class="am-img-responsive" src="'+Interface.image.pre + rowVal['cover_icon3']+'"></a></div>';
			 $field.append($h);
			 $field.attr("link", rowVal['ad_url']);
			 $field.attr("new_id", rowVal['id']);
			 $field.attr("is_ad", rowVal['is_ad']);
		 }
	 };
	 
	//banner
	 window.replace_banner_imgurl = function ( $field, imgurl, rowVal ) {
		 	$field.attr("src", Interface.image.pre + imgurl);
		 	var id = rowVal["id"],
		 		is_go = rowVal["is_redirect"];
		 	$field.attr("ad_id", id);
		 	if(is_go == 1){
		 		if(rowVal["out_url"] !== null && rowVal["out_url"] != ""){
		 			$field.click(function(){
			 			window.location.href= rowVal["out_url"];
				 	});
		 		} else {
		 			$field.click(function(){
		 				Result.forward("../branner/detail.html", {"ad_id" : $(this).attr("ad_id")});
		 			});
		 		}
		 		 $field.addClass("phand");
		 	} 
		};
		
		
	 
		 
	
}( window ) );
